// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#ifdef POLLUX_ENABLE_ABFS
#include <pollux/common/config/Config.h>
#include <pollux/connectors/hive/storage_adapters/abfs/AbfsFileSystem.h> // @manual
#include <pollux/connectors/hive/storage_adapters/abfs/AbfsUtil.h> // @manual
#include <pollux/dwio/common/FileSink.h>
#endif

namespace kumo::pollux::filesystems {

#ifdef POLLUX_ENABLE_ABFS
melon::once_flag abfsInitiationFlag;

std::shared_ptr<FileSystem> abfsFileSystemGenerator(
    std::shared_ptr<const config::ConfigBase> properties,
    std::string_view filePath) {
  static std::shared_ptr<FileSystem> filesystem;
  melon::call_once(abfsInitiationFlag, [&properties]() {
    filesystem = std::make_shared<AbfsFileSystem>(properties);
  });
  return filesystem;
}

std::unique_ptr<pollux::dwio::common::FileSink> abfsWriteFileSinkGenerator(
    const std::string& fileURI,
    const pollux::dwio::common::FileSink::Options& options) {
  if (isAbfsFile(fileURI)) {
    auto fileSystem =
        filesystems::getFileSystem(fileURI, options.connectorProperties);
    return std::make_unique<dwio::common::WriteFileSink>(
        fileSystem->openFileForWrite(fileURI),
        fileURI,
        options.metricLogger,
        options.stats);
  }
  return nullptr;
}
#endif

void registerAbfsFileSystem() {
#ifdef POLLUX_ENABLE_ABFS
  registerFileSystem(isAbfsFile, std::function(abfsFileSystemGenerator));
  dwio::common::FileSink::registerFactory(
      std::function(abfsWriteFileSinkGenerator));
#endif
}

} // namespace kumo::pollux::filesystems
